<template>
  <div id="globalHeader">
    <a-row :wrap="false">
      <a-col flex="200px">
        <router-link to="/">
          <div class="title-bar">
            <img class="logo" src="../assets/xianrendong-logo.png" alt="logo" />
            <div class="title">仙人洞文旅</div>
          </div>
        </router-link>
      </a-col>
      <a-col flex="auto">
        <a-menu mode="horizontal" :selected-keys="selectedKey" @click="handleMenuClick">
          <a-menu-item class="menuItem" v-for="item in visibleRoutes" :key="item.path"
            >{{ item.name }}
          </a-menu-item>
        </a-menu>
      </a-col>
      <a-col flex="120px">
        <div class="user-login-status">
          <div v-if="loginUserStore.loginUser.id">
            <a-dropdown>
              <a-space>
                <a-avatar :src="loginUserStore.loginUser.userAvatar" />
                {{ loginUserStore.loginUser.userName ?? '无名' }}
              </a-space>
              <template #overlay>
                <a-menu>
                  <a-menu-item @click="showUserProfile">
                    <UserOutlined />
                    关于我的
                  </a-menu-item>
                  <a-menu-item @click="doLogout">
                    <LogoutOutlined />
                    退出登录
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </div>
          <div v-else>
            <a-button type="primary" href="/user/login">登录</a-button>
          </div>
        </div>
      </a-col>
    </a-row>

    <!-- 个人信息编辑模态框 -->
    <a-modal
      v-model:open="userProfileModalVisible"
      title="个人信息"
      width="600px"
      @cancel="handleUserProfileCancel"
    >
      <UserProfileForm
        ref="userProfileFormRef"
        :user-info="loginUserStore.loginUser"
        @success="handleUserProfileSuccess"
      />

      <template #footer>
        <div style="text-align: right; margin-top: 16px">
          <a-space>
            <a-button @click="handleUserProfileCancel">取消</a-button>
            <a-button @click="handleUserProfileReset">重置</a-button>
            <a-button
              type="primary"
              :loading="userProfileSubmitting"
              @click="handleUserProfileSubmit"
            >
              保存
            </a-button>
          </a-space>
        </div>
      </template>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
import { computed, ref } from 'vue'
import { LogoutOutlined, UserOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import { userLogout } from '@/api/userController.ts'
import UserProfileForm from './UserProfileForm.vue'

const loginUserStore = useLoginUserStore()

import checkAccess from '@/access/checkAccess.ts'
import { routes } from '@/router/routes.ts'

const router = useRouter()
const visibleRoutes = computed(() => {
  return routes.filter((item) => {
    if (item.meta?.hideinmenu) {
      return false
    }
    //根据权限过滤菜单
    if (!checkAccess(loginUserStore.loginUser, item.meta?.access as string[])) {
      return false
    }
    return true
  })
})
// 当前选中的菜单, 默认主页
const selectedKey = ref(['/'])

// 个人信息模态框状态
const userProfileModalVisible = ref(false)
const userProfileSubmitting = ref(false)
const userProfileFormRef = ref()

// 监听路由变化
router.afterEach((to) => {
  selectedKey.value = [to.path]
})

//路由跳转事件
const handleMenuClick = ({ key }: { key: string }) => {
  router.push({
    path: key,
  })
}

// 显示个人信息模态框
const showUserProfile = () => {
  userProfileModalVisible.value = true
}

// 处理个人信息编辑成功
const handleUserProfileSuccess = async () => {
  userProfileModalVisible.value = false
  userProfileSubmitting.value = false

  // 重新获取用户信息
  try {
    await loginUserStore.fetchLoginUser()
    message.success('个人信息已更新')
  } catch {
    message.error('刷新用户信息失败')
  }
}

// 关闭个人信息模态框
const handleUserProfileCancel = () => {
  userProfileModalVisible.value = false
  userProfileSubmitting.value = false
}

// 重置个人信息表单
const handleUserProfileReset = () => {
  if (userProfileFormRef.value) {
    userProfileFormRef.value.handleReset()
  }
}

// 提交个人信息表单
const handleUserProfileSubmit = async () => {
  if (userProfileFormRef.value) {
    userProfileSubmitting.value = true
    try {
      await userProfileFormRef.value.handleSubmit()
    } catch {
      userProfileSubmitting.value = false
    }
  }
}

// 用户注销
const doLogout = async () => {
  const res = await userLogout()
  if (res.data.code === 200) {
    // loginUserStore.setLoginUser({
    //   userName: '未登录',
    // })
    loginUserStore.clearState()
    message.success('退出登录成功')
    await router.push('/user/login')
  } else {
    message.error('退出登录失败，' + res.data.message)
  }
}
</script>

<style scoped>
#globalHeader .title-bar {
  display: flex;
  align-items: center;
}

.title {
  color: black;
  font-size: 18px;
  margin-left: 16px;
}

.logo {
  height: 48px;
}
</style>
